package md.sv.dbu.mq;

import com.ibm.mq.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MQSender {
    private static final Logger logger = LoggerFactory.getLogger(MQSender.class);

    private MQQueueManager qMgr;
    private String managerName = null; // "your_Q_manager"
    private String queueName = null; // remote queue on RU


    public MQSender(String managerName, String queueName) {
        this.managerName = managerName;
        this.queueName = queueName;
    }

    public boolean connect() {
        try {
            qMgr = new MQQueueManager(managerName);
            logger.info("... MQ is connected !!! ........" + managerName + "." + queueName);
        } catch (MQException ex) {
            logger.error("An MQ(" + managerName + "." + queueName + ") error  occurred in init(): Completion code "
                    + ex.completionCode + " Reason code"
                    + ex.reasonCode);
            close();
            return false;
        }

        return true;
    }

    public void close() {
        try {
            if (qMgr != null)
                qMgr.disconnect();

            logger.info("... MQ is closed !!! ................................................");

        } catch (MQException e) {
            logger.error("An MQ error occurred in init() while disconnecting: Completion code "
                    + e.completionCode + " Reason code" + e.reasonCode);
        }
    }

    public boolean send(String message, boolean byteMessage) {
        if (message == null) return false;
        try {
            if (qMgr == null) {
                logger.warn("..... Error MQ Manager is not connected !!!");
                return false;
            }

            int openOptions = MQC.MQOO_OUTPUT;

            MQQueue remoteQueue = qMgr.accessQueue(queueName, openOptions, managerName, null, null);


            MQMessage msgForSend = new MQMessage();

            if (byteMessage) {
                msgForSend.format = MQC.MQFMT_NONE;
                msgForSend.write(message.getBytes("UTF-8"));
            } else {
                msgForSend.format = MQC.MQFMT_STRING;
                msgForSend.writeUTF(message);
            }


            MQPutMessageOptions pmo = new MQPutMessageOptions();
            remoteQueue.put(msgForSend, pmo);

            remoteQueue.close();

            return true;
        } catch (Exception e) {
            logger.error("..MQ..MQException error=", e);
        }
        return false;
    }

}
